/*
 * Log.h
 *
 *  Created on: Feb 9, 2010
 *      Author: Jamie LaPointe
 */

#ifndef LOG_H_
#define LOG_H_

#include <string>
#include <iostream>
#include <fstream>
#include <pthread.h>

namespace Logger
{

class Log
{
private:
   std::ofstream * outfile;
   pthread_mutex_t printMutex;

   Log(const Log &);
   Log & operator=(const Log &);
public:
   Log()
   {
      //
      // Open file truncated (delete existing data) and set for output only.
      //
      outfile = new std::ofstream("log.txt", std::ios::trunc | std::ios::out);
      if (outfile == 0)
      {
         std::cerr << "Log file could not be opened!!!!" << std::endl;
         exit(1);
      }
      pthread_mutex_init(&printMutex, 0);
   }

   ~Log()
   {
      //
      // cleanup file pointer.
      //
      if (outfile != 0)
      {
         outfile->close();
         delete(outfile);
         outfile = 0;
      }

      pthread_mutex_destroy(&printMutex);
   }

   void writeLine(std::string message)
   {
      pthread_mutex_lock(&printMutex);
      if (outfile != 0)
      {
         (*outfile) << message << std::endl;
         outfile->flush();
         pthread_mutex_unlock(&printMutex);
      }
      else
      {
         std::cerr << "Log file is closed!!!!" << std::endl;
         pthread_mutex_unlock(&printMutex);
         exit(1);
      }
   }
}; // class Log

} // namespace Logger

#endif /* LOG_H_ */
